
;(function () {

    var init={
        totalnum:function (event) {
            var target  = event.target,total=0,
                className = $(target).parent().parent()[0].className;
            var total_num =  parseInt($('.'+className).find('.total_num').val());// 总数量

            //已到货数量
            var arrived_num = parseInt($('.'+className).find('.arrived_num').val())?parseInt($('.'+className).find('.arrived_num').val()):0;
            var //应到货数量
                yd  = parseInt($('.'+className).find('.should_num').val()),
                // 实到货数量
                sd  = parseInt($('.'+className).find('.actual_num').val())?parseInt($('.'+className).find('.actual_num').val()):0,// 实到货数量
                // 验收入库数量
                ys  = parseInt($('.'+className).find('.check_num').val())?parseInt($('.'+className).find('.check_num').val()):0,
                //退货数量
                th   = parseInt($('.'+className).find('.return_num').val())?parseInt($('.'+className).find('.return_num').val()):0,
                //需补货数量
                xbh   = parseInt($('.'+className).find('.replenishment_num').val());

            
            var shou=0;
            if (total_num - yd ==0 ){
                shou =  (total_num - yd)+ys;
            }else {
                shou =  (total_num - yd)+ys;
            }
            if (yd < ys) {
                layer.msg('验收入库数量不能大于应到货数量！', {icon: 3});
            }else if (sd  < ys ) {
                layer.msg('验收入库数量不能大于实到货数量！', {icon: 3});
            } else {
                $('.'+className).find('.arrived_num').val(shou);
                $('.'+className).find('.arrived_num').text(shou);
                $('.'+className).find('.replenishment_num').val(((yd-sd)+th));
            }
        },
        openIframeLayer:function (href,title) {
            openIframeLayer(href, title, {
                area: ['90%', '80%'],
                // btn: ['确定', '取消'],
                yes: function (index, layero) {
                }
            })
        },
        onAddBtn:function(){
            //页面层-自定义
            layer.open({
                type: 1,
                title:"导入数据",
                closeBtn: false,
                shift: 2,
                area: ['400px', '300px'],
                shadeClose: true,
                // btn: ['新增', '取消'],
                // btnAlign: 'c',
                content: $("#add-main"),
                success: function(layero, index){},
                yes:function(){
                }
            });
        } ,
        partTable:function (href,total_num) {
            var columns=[];
            var dataList = [];

            $('#product_part').bootstrapTable({
                url: href,
                pageNumber: 1, //初始化加载第一页
                pagination: false,//是否分页
                sidePagination: 'server',//server:服务器端分页|client：前端分页
                showRefresh: false,//刷新按钮
                showColumns:  false, //
                editable: true,
                idField: 'pro_part_id', //指定主键
                columns: [
                    {checkbox:true},
                    {field: 'iname', title: '构件名称', align: 'center',},
                    {field: 'spes', title: '规格（mm）', align: 'center',
                        formatter: function (value, row, index) {
                            return row.iwidth+'*'+row.iheight+'*'+row.ithick;
                        }},
                    {field: 'stuff_name', title: '材质', align: 'center',},
                    {field: '', title: '合成所需数量', align: 'center',
                        formatter: function (value, row, index) {
                            return row.inumber * total_num
                        }},
                    {field: '', title: '单位', align: 'center',  formatter: function (value, row, index) {
                            return '件';
                        }},
                    {field: 'synthesis_num', title: '应到货数量', align: 'center',  formatter: function (value, row, index) {
                            return ' <input type="hidden" class="synthesis_num" id="synthesis_num"   name="product['+index+'][synthesis_num]" id="synthesis_num_'+index+'" value="'+row.inumber * total_num+'"/>'+row.inumber * total_num;
                        }},
                    {field: 'should_num', title: '实到货数量', align: 'center',  formatter: function (value, row, index) {var num = (row.inumber * total_num)
                            return     ' <input type="hidden" class="should_num"   name="product['+index+'][should_num]" id="should_num_'+index+'" value="'+num+'"/>'+num;
                        }},
                    {field: 'check_num', title: '验收入库数量', align: 'center', formatter: function (value, row, index) {
                            return '<input type="text" class="form-control check_num"   name="product['+index+'][check_num]" style="width: 80px;" id="check_num_'+index+'" data-index="'+index+'"  value="'+value+'" />';
                        }},
                    {field: 'return_num', title: '退货数量', align: 'center', editable: {canEdit: true,type:'text', }, formatter: function (value, row, index) {
                        // return '<input type="text" class="form-control return_num"  name="product['+index+'][return_num]"  style="width: 80px;" id="return_num_'+index+'" data-index="'+index+'"   value="'+value+'" />';
                            return value;
                    }},
                    {field: 'replenishment_num', title: '需补货数量', align: 'center',formatter: function (value, row, index) {
                            return '<input type="text" class="form-control replenishment_num"  name="product['+index+'][replenishment_num]"  id="replenishment_num_'+index+'" style="width: 80px;" data-index="'+index+'"  value="'+value+'" />';
                        }},
                    {
                            field: 'operate',
                            title: '操作',
                            align: 'center',
                            events: "operateEvents",
                            formatter: function (value, row, index) {
                                var href='';

                                    href+= ' <a href="javascript:"   class="RoleOfA">  退货原因</a>  '

                                    href+= ' <a href="javascript:" class="RoleOfK">  备注信息</a>  '

                                href+= ' <a href="javascript:" class="RoleOfB">历史记录</a>'
                                return href;
                            }
                        },
                ],
                formatLoadingMessage: function () {
                    return "数据正在加载中...";
                },
                formatNoMatches: function () {
                    return '无符合条件的记录';
                },

            });
        },
    };
    $("#include").change(function(){
        if($("#include").is(":checked")){
            $("#payfor").attr('disabled','disabled');
        }else{
            $("#payfor").removeAttr('disabled');
        }
    })

    $("#tax").change(function(){
        if($("#tax").is(":checked")){
            $("#tax_price").attr('disabled','disabled');
        }else{
            $("#tax_price").removeAttr('disabled');
        }
    })
    $('.lock-pro_info').click(function () {
        var href = $(this).data('href'),
            title = $(this).data('title');
        init.openIframeLayer(href,title)
    });
    $('.pro_name').click(function () {
        var pro_id = $(this).data('pro_id'),
            po_id = $(this).data('po_id'),
            href = $(this).data('href'),
            purchase_id = $(this).data('purchase_id'),
            p_order_id = $(this).data('p_order_id'),
            history_record = $(this).data('history_record'),
            // total_num = $(this).data('total_num'),
            sy = $(this).data('sy');//剩余套数

        console.log($(this).data('total_num'))
        console.log($(this).data('match_actual'))
        console.log($(this).data('total_num') <= $(this).data('match_actual'))
        if ($(this).data('total_num') <= $(this).data('match_actual')) {
            $('#check-synthesis').css('display','none');
        }else {
            $('#check-synthesis').css('display','');
        }

        //ajax请求去获取对应分类的信息
        $.ajax({
            url		: href,
            type	: "get",
            dataType: "json",
            success : function(result) {
                if (result.rows.length == 0) {
                    $("#product_info").html('');
                    return;
                }
                $("#product_info").html('');
                var html = "";
                $.each(result.rows, function (i, n) {
                    // var total_inumber=n.inumber * sy,
                    var  p_total_num = n.total_num,
                         total_inumber= n.total_num - n.arrived_num,
                        arrived_num=0,// 已到到货
                        actual_num=0,// 实际到货
                        check_num=0, // 验收入库
                        return_num=0,// 退货数量
                        remark='',//备注
                        reason_return='',//  	退货原因
                        replenishment_num=0;
                    // if ((n.actual_num-n.check_num)==0){
                    //     total_inumber= (n.inumber * total_num)- n.arrived_num;
                    // }else {
                    //     total_inumber=n.inumber * sy;
                    // }
                    // if(n.total_num!=null){  total_inumber = n.total_num }
                    if(n.arrived_num!=null){  arrived_num = n.arrived_num }//
                    if(n.actual_num!=null){  actual_num = n.actual_num }
                    if(n.check_num!=null){  check_num = n.check_num }
                    if(n.return_num!=null){  return_num = n.return_num }
                    if(n.replenishment_num!=null){  replenishment_num = n.replenishment_num}
                    if(n.reason_return!=null){  reason_return = n.reason_return}
                    if(n.remark!=null){  remark = n.remark}

                    html+='<tr class="info_id_'+n.id+'">\n' +
                        '     <td><input type="checkbox" class="js-check pro_part_id"  data-index="'+i+'"  data-yid="js-check-y" data-xid="js-check-x" ' +
                        'value="'+n.id+'" name=product['+i+'][pro_part_id]"></td>\n' +
                        '     <td>' +
                        '<input type="hidden" class="purchase_id" data-index="'+i+'"  name="product['+i+'][purchase_id]"  value="'+purchase_id+'"/>' +
                        '<input type="hidden" class="pro_id" data-index="'+i+'"  name="product['+i+'][pro_id]" value="'+pro_id+'"/>' +
                        '<input type="hidden" class="spec" data-index="'+i+'"  name="product['+i+'][spec]" value="'+n.iwidth+'*'+n.iheight+'*'+n.ithick+'"/>' +
                        '<input type="hidden" class="stuff_name" data-index="'+i+'"  name="product['+i+'][stuff_name]" value="'+n.stuff_name+'"/>' +
                        '<input type="hidden" class="inumber" data-index="'+i+'"  name="product['+i+'][inumber]" value="'+n.inumber+'"/>' +
                        '<input type="hidden" class="total_num" data-index="'+i+'"  name="product['+i+'][total_num]" value="'+p_total_num+'"/>' +
                        '<input type="hidden" class="remark" data-index="'+i+'"  name="product['+i+'][remark]" value="'+remark+'"/>' +
                        '<input type="hidden" class="reason_return" data-index="'+i+'"  name="product['+i+'][reason_return]" value="'+reason_return+'"/>' +
                        '<input type="hidden" class="iname" data-index="'+i+'"  name="product['+i+'][iname]" value="'+n.iname+'"/>' +n.iname+'</td>\n' +
                        '     <td>'+n.iwidth+'*'+n.iheight+'*'+n.ithick+'</td>\n' +
                        '     <td>'+n.stuff_name+'</td>\n' +
                        '     <td> ' +
                        ' <input type="hidden" class="synthesis_num" data-index="'+i+'"  name="product['+i+'][synthesis_num]" value="'+n.inumber+'"/> ' +
                        '          <label style="font-weight: normal;" class="synthesis_num">'+n.inumber+'</label> </td>\n' +
                        '     <td>件</td>\n' +
                        '     <td>' +
                        '        <input type="hidden" class="arrived_num" data-index="'+i+'"  name="product['+i+'][arrived_num]" value="'+arrived_num +'"/> ' +
                        '        <label style="font-weight: normal;" class="arrived_num">'+arrived_num+'</label>' +
                        '       </td>\n' +
                        '     <td>' +
                        '        <input type="hidden" class="should_num" data-index="'+i+'"  name="product['+i+'][should_num]" value="'+total_inumber+'"/> ' +
                        '        <label style="font-weight: normal;" class="should_num">'+total_inumber+'</label>' +
                        '       </td>\n' +
                        '     <td><input type="text" class="form-control actual_num" data-index="'+i+'" style="width: 80px;" name="product['+i+'][actual_num]" value="0"></td>\n' +
                        '     <td><input type="text" class="form-control check_num" data-index="'+i+'"  style="width: 80px;"name="product['+i+'][check_num]" value="0"></td>\n' +
                        '     <td><input type="text" class="form-control return_num" data-index="'+i+'"  style="width: 80px;"name="product['+i+'][return_num]" value="0"></td>\n' +
                        '     <td><input type="text" class="form-control replenishment_num"  data-index="'+i+'"  style="width: 80px;"name="product['+i+'][replenishment_num]" value="0"></td>\n' +
                        '     <td>' +
                        '       <a href="javascript:;" class="reason_return_" >退货原因 </a>|\n' +
                        '       <a href="javascript:;" class="remark_" >备注信息</a>|\n' +
                        '       <a href="javascript:;" data-title="历史记录（'+n.iname+'）" data-href="'+history_record+'?type=2&part_id='+n.id+'&purchase_id='+purchase_id+'" class="lock-pro_info" >历史记录</a>\n' +
                        '      </td>\n' +
                        '</tr>'
                });
                $("#product_info").html(html);
                $("#po_id").val(po_id);
                $("#pro_id").val(pro_id);
            }
        })
    })

    $("#product_info").on("input propertychange change",function(event){
    });

    $('.js-check-all').click(function (e) {
        var name = $(".js-check");
        if($(this).is(':checked')){
            for(var i=0;i<name.length;i++){
                name[i].checked=true ;
            }
        }else {
            for(var i=0;i<name.length;i++){
                name[i].checked=false ;
            }
        }
    });
    $(document).on('click','.saved',function(event) {
        var target  = event.target,
            className = $(target).parent().parent()[0].id;
        $('#'+className).remove()
    })
    $('#product_info').on('click','.reason_return_',function(event){
        var target  = event.target,
            className = $(target).parent().parent()[0].className;
        var simg_url = $('.'+className).find('.reason_return').val()

        var lis = '';
        if (simg_url)
            $.each(JSON.parse(simg_url),function(i,obj) {
                lis+='<li id="saved-image1id'+i+'" style="width: 202px;float:left;height: 172px;text-align: center">\n' +
                    '            <p class="imgWrap">\n' +
                    '                <input id="photo-'+i+'" type="hidden" name="photo_urls1[]" class="hidden" value="'+obj+'">\n' +
                    '                <img id="photo-'+i+'-preview" src="/upload/'+obj+'" style="width: 100%;" onclick="imagePreviewDialog(this.src);">\n' +
                    '            </p>\n' +
                    '            <p>\n' +
                    '            <a href="javascript:;" class="saved" data-key="'+i+'" style="font-size: 12px">移除</a>\n' +
                    '            </p>\n' +
                    '        </li>'
            })
        //页面层-自定义
        layer.open({
            type: 1,
            title:"上传图片",
            closeBtn: true,
            shift: 2,
            area: ['80%', '70%'],
            shadeClose: false,
            btn: ['确认', '取消'],
            content: '  <form method="post" class="form-horizontal ">\n' +
                '            <div class="form-group" style="margin:10px 0" >\n' +
                '                <div class="col-lg-12">\n' +
                '                    <label class="control-label"></label>\n' +
                '                    <a class="btn btn-primary" href="javascript:uploadMultiImage(\'图片上传\',\'#photos\',\'photos-item-tpl\');">选择图片</a><span class="form-required">*</span>\n' +
                '                </div>\n' +
                '                </div><div class="form-group" style="margin:10px 0">' +
                '                    <div class="col-lg-12">\n' +
                '                        <ul id="photos" class="pic-list list-unstyled form-inline">\n' +lis+
                '                        </ul>\n' +
                '                    </div>\n' +
                '</div>\n' +
                '        </form> ',
            yes:function(index, layero){
                var img_url ='';
                var arrayObj = new Array();
                var photo_urls1 = $('input[name="photo_urls1[]"]').each(function (r,i) {
                    arrayObj. push(i.value)
                });
                $('.'+className).find('.reason_return').val();
                $('.'+className).find('.reason_return').val(JSON.stringify(arrayObj));
                $('#photos').html('');
                layer.close(index)
            }
        });
    })
    $('#product_info').on('click','.remark_',function(event){
        var target  = event.target,
            className = $(target).parent().parent()[0].className;
        var remark = $('.'+className).find('.remark').val()
        var iname = $('.'+className).find('.iname').val()
        layer.prompt({
            formType: 2,
            title: '备注信息('+iname+')',
            area: ['500px', '150px'],
            btnAlign: 'c',
            value: remark,
        }, function(value, index, elem){
            $('.'+className).find('.remark_').attr("title",value)
            $('.'+className).find('.remark').val(value)
            layer.close(index);
        });
    });
    $('#product_info').on('click','.lock-pro_info',function(event){
        var href = $(this).data('href'),
            title = $(this).data('title');
        init.openIframeLayer(href,title)
    });
    $('#product_info').on('blur','.check_num',function(event){
        init.totalnum(event)
    });
    $('#product_info').on('blur','.actual_num',function(event){
        init.totalnum(event)
    });
    $('#product_info').on('blur','.return_num',function(event){
        init.totalnum(event)
    });
    $('#check-synthesis').click(function () {
        var arrObj = new Array();
        // $('.check_num').each(function (i,n) {
        //     arrObj. push(n.value)
        // });
        var pro_id = $('#pro_id').val(),
            pro_name = $('.pro_id_'+pro_id).find('.pro_name'),//订单数量
            total_num =pro_name.data('total_num'),//订单数量
            match_actual =pro_name.data('match_actual'),//订单数量
            sy =pro_name.data('sy'),//订单数量
            sj_match_actual =  $('.pro_id_'+pro_id).find('.match_actual').text(),//实际合成数量
            match_not = $('.pro_id_'+pro_id).find('.match_not').val();//未合成数量


        console.log('实际到货数量 ：'+pro_id)
        console.log('实际到货数量 ：'+sj_match_actual)

        var sy = total_num - match_actual;//剩余套数

        $('#product_info tr').each(function (i,n) {
            var iname = ($('.'+n.className).find('.iname').val()),
                inumber =$('.'+n.className).find('.inumber').val(),// 单个数量
                ydh = parseInt($('.'+n.className).find('.arrived_num').val()),// 已到货数量
                hc = parseInt($('.'+n.className).find('.synthesis_num').val()),// 合成所需数量
                yd =parseInt($('.'+n.className).find('.should_num').val()),// 应到货数量
                sd =parseInt($('.'+n.className).find('.actual_num').val()),// 实到货数量
                ys =parseInt($('.'+n.className).find('.check_num').val()),// 验收数量
                th =parseInt($('.'+n.className).find('.return_num').val()),// 退货数量
                xbh =parseInt($('.'+n.className).find('.replenishment_num').val());// 需补货数量
            //已到货数量 - （所需数量 * 已合成数量）
            var hc_num = ydh - (inumber * sj_match_actual)

            console.log('-----------------------------------------------------------------------------------------------------------------------------------------------------------------')
            console.log("已到货数量:" +ydh+ " /实际合成数量:"+ sj_match_actual +" /单个数量"+inumber)
            console.log("已到货数量:" +ydh+ " /实际合成数量:"+ sj_match_actual +" /单个数量"+inumber)
            console.log("所需数量 * 已合成数量:" +inumber * sj_match_actual)
            console.log("已到货数量 - （所需数量 * 已合成数量）" +hc_num)
            console.log('-----------------------------------------------------------------------------------------------------------------------------------------------------------------')
            console.log("实际合成数量:" +sj_match_actual+ "- 剩余套数:" +sy+ "   "+iname+"  - 合成所需数量："+hc+"  应到货："+yd+" 实到货："+sd+"  验收数量："+ys+"  退货数量："+th+"  需补货数量："+xbh);
            console.log('-----------------------------------------------------------------------------------------------------------------------------------------------------------------')

            var ys_hc = parseInt(hc_num/hc),//已到货/合成
                ys_cg_y = parseInt(hc_num%hc);//已到货/合成-取余
            arrObj. push(ys_hc);// 入库套数合并数据
            console.log('验收/合成：'+(hc_num/hc))
            console.log('验收/合成：'+parseInt(hc_num/hc))
            console.log('验收/合成-取余：'+parseInt(hc_num%hc))

        });
        console.log(arrObj)
        var ta = arrObj.join(",").split(","),
            actual = parseInt(Math.min.apply(null, ta))+parseInt(match_actual) ;
        console.log('ta：'+ta)
        console.log('actual：'+actual)
        console.log('total_num：'+total_num) 

        if ((parseInt(total_num) -  actual)==0){
            $('.pro_id_'+pro_id).find('.status_enter').val(2);
        }
        if (parseInt(Math.min.apply(null, ta)) <= 0 ) {
            layer.msg('合成数量不能小于0',{icon:3});
        }else if (actual>total_num) {
            layer.msg('实际合成数量不能大于订单数量：'+total_num,{icon:3});
        }else {
            if (sy!=0){
                $('.pro_id_'+pro_id).find('.match_actual_num').val(actual-sj_match_actual);//实际合成数量
                $('.pro_id_'+pro_id).find('.match_actual').val(actual);//实际合成数量
                $('.pro_id_'+pro_id).find('.match_actual').text(actual);//实际合成数量
                $('.pro_id_'+pro_id).find('.match_not').val(parseInt(total_num)- actual);//未合成数量
                $('.pro_id_'+pro_id).find('.match_not').text(parseInt(total_num)-  actual);//未合成数量
                $('.pro_id_'+pro_id).find('.match_usable').val(actual);//可使用数量
                $('.pro_id_'+pro_id).find('.match_usable').text(actual);//可使用数量
            }
            $('#type').val(1)
            $.post($(".form-horizontal").attr('action'), $(".form-horizontal").serialize(), function(result){
                if(result.code == 1){
                    layer.msg("保存成功");
                    layer.alert("合成入库成功");
                    window.location.href = result.url;
                } else {
                    layer.msg(result.msg);
                }
            }, 'json');
        }
    });
    $('#check-btn').click(function () {
        $('#type').val(0)
        $.post($(".form-horizontal").attr('action'), $(".form-horizontal").serialize(), function(result){
            if(result.code == 1){
                layer.msg("保存成功");
                window.location.href = result.url;
            } else {
                layer.msg(result.msg,{icon:3});;
            }
        }, 'json');
    });
})()


